package main

import (
	"fmt"
	"os/exec"
	"path/filepath"
	"runtime"
	"sjy/customcmd/src/utils"

	"github.com/astaxie/beego/logs"
)

var ScriptRoot = getScriptRoot()
var Root = filepath.Join(ScriptRoot, "..")

type Build struct {
	AppName   string `yaml:"main_app_name"`
	SetupName string `yaml:"setup_name"`
	Version   string `yaml:"version"`
	NSISPath  string `yaml:"nsis_path"`
}

func main() {
	var date *Build
	err := utils.LoadYamlError(filepath.Join(Root, "build.yaml"), &date, func(err error) {})
	if err != nil {
		logs.Error("Load Yaml Error:", err)
		return
	}
	// build go app
	err = execPs("build_go.ps1", []string{date.AppName})
	if err != nil {
		logs.Error("Build Go App Error:", err)
		return
	}
	logs.Info("Build Go App Success!")

	// build nsis
	err = execPs("build_setup.ps1", []string{date.SetupName, date.Version, date.NSISPath})
	if err != nil {
		logs.Error("Build NSIS Error:", err)
		return
	}
	logs.Info("Build NSIS Success!")

	// 生成latest.yaml
	BuildLatest(date)
}

func execPs(script string, args []string) error {

	exec.Command("chcp", "65001").Run()

	scriptpath := filepath.Join(ScriptRoot, script)

	psargs := []string{"-ExecutionPolicy", "Bypass", "-File", scriptpath}
	psargs = append(psargs, args...)

	cmd := exec.Command("powershell", psargs...)
	output, err := cmd.CombinedOutput()
	if err != nil {
		fmt.Printf("Error executing PowerShell script: %v\n", err)
		fmt.Println(string(output))
		return err
	} else {
		fmt.Println(string(output))
		return nil
	}
}

func getScriptRoot() string {
	// 获取调用者的文件路径
	_, filename, _, _ := runtime.Caller(0)
	// 获取 main.go 所在的目录
	mainDir := filepath.Dir(filename)

	// exePath, _ := os.Executable()
	// return filepath.Dir(exePath)
	return mainDir
}
